package com.Jeu;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

class Timer extends SurfaceView implements SurfaceHolder.Callback {
	private int Time = 40;
	public static int currentTime;

	class CounterThread extends Thread {
		private boolean isRunning;
		private int counter = 0;
		// private int currentTime = 0;
		// private int modeTime = 20;
		private SurfaceHolder refSurfaceHolder;
		private Paint textPaint;

		public CounterThread(SurfaceHolder surfaceHolder) {
			refSurfaceHolder = surfaceHolder;
			textPaint = new Paint();
			textPaint.setARGB(255, 0, 255, 0);
			textPaint.setTextSize(12);

		}

		@Override
		public void run() {
			isRunning = NewGame.run;
			while (isRunning) {
				Canvas c = null;
				try {
					c = refSurfaceHolder.lockCanvas(null);
					synchronized (refSurfaceHolder) {
						updateTimer();
						doDraw(c);
						// if (counter == 1000) {
						// isRunning = false;
						// }
					}
				} finally {
					if (c != null) {
						refSurfaceHolder.unlockCanvasAndPost(c);
					}
				}
			}
		}

		private void updateTimer() {
			isRunning = NewGame.run;
			if (isRunning)
				counter += 1;
		}

		private void doDraw(Canvas canvas) {
			canvas.drawColor(Color.WHITE);
			Time = getTime();
			currentTime = Time - Math.round(counter / 100);
			canvas.drawText("Time : " + currentTime, 5, 15, textPaint);
			canvas.restore();
		}

		public void setRunning(boolean b) {
			isRunning = b;
		}

	}

	private CounterThread thread;

	public int getTime() {
		// ModeGame mode = new ModeGame();
		// return ((.ModeGame) this.getApplica()).getTimer();
		return ModeGame.modeTime;
		// return mode.getTime();
	}

	public Timer(Context context, AttributeSet attrs) {
		super(context, attrs);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		thread = new CounterThread(holder);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		thread.setRunning(false);
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}
}
